/*******************************************************************************
 *                                    ZLG
 *                         ----------------------------
 *                         innovating embedded platform
 *
 * Copyright (c) 2001-presnet Guangzhou ZHIYUAN Electronics Co., Ltd.
 * All rights reserved.
 *
 * Contact information:
 * web site:    https://www.zlg.cn
 *******************************************************************************/
/*******************************************************************************
 * Includes
 ******************************************************************************/
#include <stdio.h>
#include "core/include/hc32f4a0_regs_sram.h"
#include "core/include/hc32f4a0_sram.h"
#include "common/hc32f4a0_errno.h"

/*******************************************************************************
 * Code
 ******************************************************************************/
/**
 * \brief 设置 SRAM 等待周期
 *
 * \param[in] sram_idx    要设置的 SRAM 索引
 * \param[in] write_cycle 写等待周期
 * \param[in] read_cycle  读等待周期
 *
 * \retval 成功返回OK
 */
int sram_wait_cycle_set(uint32_t sram_idx, uint32_t write_cycle, uint32_t read_cycle){
    uint8_t  i;
    uint8_t  write_offset;
    uint8_t  read_offset;
    uint32_t sram_list[4] = {SRAM_SRAM123, SRAM_SRAM4, SRAM_SRAMH, SRAM_SRAMB};

    /* 读写参数周期*/
    if ((!IS_SRAM_CYCLE(write_cycle)) || (!IS_SRAM_CYCLE(read_cycle))) {
        return -EINVAL;
    }
    /* 检查 SRAM 寄存器是否写使能*/
    if (HC32F4A0_SRAM->WTPR != SRAM_UNLOCK_CMD) {
        return -EPERM;
    }

    for (i = 0; i < 4; i++) {
        if ((sram_idx & sram_list[i]) != 0) {
            write_offset = i << 3;
            read_offset = write_offset + 4;
            MODIFY_REG32(HC32F4A0_SRAM->WTCR,
                       ((SRAM_CYCLE_MSK << write_offset) | (SRAM_CYCLE_MSK << read_offset)),
                       ((write_cycle << write_offset) | (read_cycle << read_offset)));
        }
    }

    return 0;
}
